import time

from google.protobuf.empty_pb2 import Empty

import grpc
import peewee

from search_user_srv.proto.sys_admin import sys_admin_pb2, sys_admin_pb2_grpc
from search_user_srv.model.models import SysUser
from search_user_srv.utils.utils import pbkdf2_verify, pbkdf2_encry, create_sn
from search_user_srv.utils.grpc_utils import response_fail
from loguru import logger


class SysAdminServicer(sys_admin_pb2_grpc.SysAdminServicer):
    def GetUserList(self, request, context):
        rsp = sys_admin_pb2.SysUserListRsp()
        sys_admin = SysUser().select()

        if request.username:
            sys_admin = sys_admin.where(SysUser.username % f"%{request.username}%")
        if request.nickname:
            sys_admin = sys_admin.where(SysUser.nickname % f"%{request.nickname}%")
        rsp.total = sys_admin.count()

        offset = 0  # 偏移量
        page = 1  # 第几页
        limit = 10  # 每页显示多少条
        if request.page:
            page = request.page
        if request.limit:
            limit = request.limit
            offset = limit * (page - 1)
        sys_admin = sys_admin.limit(limit).offset(offset)
        for item in sys_admin:
            rsp.data.append(self.to_sys_user_info_rsp(item))

        return rsp

    # 包装为返回类型
    def to_sys_user_info_rsp(self, user):
        rsp = sys_admin_pb2.SysUserInfo()
        rsp.id = user.id
        rsp.username = user.username
        rsp.status = user.status
        rsp.headUrl = user.head_url
        rsp.nickname = user.nickname
        return rsp

    @logger.catch
    def GetUserByName(self, request: sys_admin_pb2.SysUserInfo, context):
        rsp = sys_admin_pb2.SysUserInfo()
        try:
            sys_admin = SysUser.get(SysUser.username == request.username)
            return self.to_sys_user_info_rsp(sys_admin)
        except peewee.DoesNotExist:
            response_fail(context, grpc.StatusCode.NOT_FOUND, "用户不存在")
            return rsp

    @logger.catch
    def GetUserById(self, request: sys_admin_pb2.SysUserInfo, context):
        rsp = sys_admin_pb2.SysUserInfo()
        try:
            sys_admin = SysUser.get(SysUser.id == request.id)
            return self.to_sys_user_info_rsp(sys_admin)
        except peewee.DoesNotExist:
            response_fail(context, grpc.StatusCode.NOT_FOUND, "用户不存在")
            return rsp

    @logger.catch
    def CheckPassword(self, request: sys_admin_pb2.SysUserInfo, context):
        try:
            sys_admin = SysUser.get(SysUser.username == request.username)
            ok = pbkdf2_verify(sys_admin.password, request.password, sys_admin.salt)
            if not ok:
                response_fail(context, grpc.StatusCode.INVALID_ARGUMENT, "用户名或密码不正确!")
                return sys_admin_pb2.CheckRsp(success=False)
            return sys_admin_pb2.CheckRsp(success=True)
        except peewee.DoesNotExist:
            response_fail(context, grpc.StatusCode.NOT_FOUND, "用户不存在")
            return sys_admin_pb2.CheckRsp(success=False)
        except Exception as e:
            response_fail(context, grpc.StatusCode.NOT_FOUND, f"内部异常:{str(e)}")
            return sys_admin_pb2.CheckRsp(success=False)

    @logger.catch
    def UpdateUser(self, request: sys_admin_pb2.SysUserInfo, context):
        try:
            sys_admin = SysUser.get(SysUser.id == request.id)
            if request.headUrl:
                sys_admin.head_url = request.headUrl
            if request.password:
                sys_admin.password = pbkdf2_encry(request.password, sys_admin.salt)
            if request.nickname:
                sys_admin.nickname = request.nickname
            sys_admin.save()
            return Empty()
        except peewee.DoesNotExist:
            response_fail(context, grpc.StatusCode.NOT_FOUND, "用户不存在")
            return Empty()
        except Exception as e:
            response_fail(context, grpc.StatusCode.INTERNAL, f"内部异常：{str(e)}")
            return Empty()

    def CreateUser(self, request: sys_admin_pb2.SysUserInfo, context):
        try:
            sys_admin = SysUser.get(SysUser.username == request.username)
            response_fail(context, grpc.StatusCode.ALREADY_EXISTS, "用户已存在")
            return sys_admin_pb2.SysUserInfo()
        except peewee.DoesNotExist:
            pass

        from search_user_srv.utils.utils import create_sn
        salt = create_sn("S", 6);
        sys_admin = SysUser()
        sys_admin.username = request.username
        sys_admin.head_url = request.headUrl
        sys_admin.password = pbkdf2_encry(request.password, salt)
        sys_admin.nickname = request.nickname
        sys_admin.salt = salt
        sys_admin.save()
        return self.to_sys_user_info_rsp(sys_admin)

    @logger.catch
    def UpdateUserStatus(self, request: sys_admin_pb2.StatusRequest, context):
        try:
            sys_admin = SysUser.get(SysUser.id == request.id)
            sys_admin.status = request.status
            sys_admin.save()
            return Empty()
        except peewee.DoesNotExist:
            response_fail(context, grpc.StatusCode.NOT_FOUND, "用户不存在")
            return Empty()

    def DeleteUser(self, request, context):
        try:
            SysUser.get(SysUser.id == request.id)
            SysUser.delete().where(SysUser.id == request.id)
            return Empty()
        except peewee.DoesNotExist:
            response_fail(context, grpc.StatusCode.NOT_FOUND, "用户不存在")
            return Empty()
